package es.unileon.is.finalproyect.userinterface;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.*;

import es.unileon.is.finalproyect.users.Group;
import es.unileon.is.finalproyect.users.User;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SelectGroupDialog extends JDialog {

	private Map<Group, JCheckBox> _map= new HashMap<Group,JCheckBox>();
	private List<Group> _groupList;


	/**
	 * Create the dialog.
	 */
	public SelectGroupDialog(User u, JFrame parent, boolean modal) {
		super(parent, modal);
		_groupList = new ArrayList<Group>();
		
		List<Group> groups;
		if(u!=null){
			groups = u.getAssignedGroups();
		} else {
			groups = new ArrayList<Group>();
		}
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout());
		
		
		//a getContentPane en NORTH una etiqueta con Seleciona los grupos que quiera filtrar (ingles)
		//en center un JscrollPane con una JPaneldentro, con tantas etiquetas y checkbox como grupos en la lista
		//en south los botones de OK y CANCEL
		
		
		JLabel title = new JLabel("Select desired groups");
		getContentPane().add(title,BorderLayout.NORTH);
		JPanel centerPanel = new JPanel(null);
		JScrollPane scroll = new JScrollPane(centerPanel);
		getContentPane().add(scroll,BorderLayout.CENTER);
		int y=10;
		int x=10;
		
		for(Group g:groups){			
			JCheckBox ch = new JCheckBox(g.getName());
			int width = (int)ch.getPreferredSize().getWidth();
			int height = (int) ch.getPreferredSize().getHeight();
			ch.setBounds(x, y, width, height);
			y += height + 10;
			centerPanel.add(ch);
			_map.put(g,ch);
		}
		
		centerPanel.setPreferredSize(new Dimension(450,y));
		
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
		getContentPane().add(buttonPane, BorderLayout.SOUTH);		
		JButton okButton = new JButton("OK");
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				okAction();
			}
		});
		okButton.setActionCommand("OK");
		buttonPane.add(okButton);
		getRootPane().setDefaultButton(okButton);
		JButton cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
		cancelButton.setActionCommand("Cancel");
		buttonPane.add(cancelButton);
		
		
		
	}
	
	private void okAction(){
		for(Map.Entry<Group, JCheckBox> entry: _map.entrySet()){
			if(entry.getValue().isSelected()){
				_groupList.add(entry.getKey());
			}			
		}
		dispose();
	}

	public List<Group> getGroupList(){
		return _groupList;
	}
}
